<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="餐馆名" prop="resName">
        <el-input
          v-model="queryParams.resName"
          placeholder="请输入餐馆名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="营业状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 200px">
          <el-option
            v-for="dict in res_open_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-select
            v-model="queryParams.categoryId"
            placeholder="请选择分类"
            clearable
            style="width: 200px"
        >
          <el-option
              v-for="category in resCategoryList"
              :key="category.categoryId"
              :label="category.categoryName"
              :value="category.categoryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:resinfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:resinfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="resinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="排序" align="center">
        <template #default="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="餐馆图片" align="center" prop="imgUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imgUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="餐馆名" align="center" prop="resName" />
      <el-table-column label="分类" align="center" prop="resCategory.categoryName" />
      <el-table-column label="所在区域" align="center" >
        <template #default="scope">
          {{ [scope.row.province, scope.row.city, scope.row.district].filter(Boolean).join('') }}
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center" prop="address" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="res_open_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:resinfo:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:resinfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改餐馆对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="resinfoRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="餐馆名" prop="resName">
          <el-input v-model="form.resName" placeholder="请输入餐馆名" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="餐馆图片" prop="imgUrl">
          <image-upload v-model="form.imgUrl"/>
        </el-form-item>
        <el-form-item label="客服电话" prop="serviceTel">
          <el-input v-model="form.serviceTel" placeholder="请设置客服电话" />
        </el-form-item>
        <el-form-item label="餐馆介绍" prop="resDesc">
          <el-input v-model="form.resDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in res_open_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="省" prop="province">
          <el-input v-model="form.province" placeholder="请输入省" />
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-input v-model="form.city" placeholder="请输入市" />
        </el-form-item>
        <el-form-item label="区" prop="district">
          <el-input v-model="form.district" placeholder="请输入区" />
        </el-form-item>
        <el-form-item label="类别" prop="categoryId">
          <el-select v-model="form.resCategory.categoryName" placeholder="请选择状态" @change="handleCategoryChange">
            <el-option
                v-for="category in resCategoryList"
                :key="category.categoryId"
                :label="category.categoryName"
                :value="category.categoryId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="餐馆公告" prop="notice">
          <el-input v-model="form.notice" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="整体评分" prop="overallScore">
          <el-input disabled v-model="form.overallScore" placeholder="请输入整体评分" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Resinfo">
import {
  listResinfo,
  getResinfo,
  delResinfo,
  addResinfo,
  updateResinfo,
  listResCategory
} from "@/api/system/resinfo"

import useUserStore from "@/store/modules/user.js";

const userStore = useUserStore()
console.log(userStore)

const { proxy } = getCurrentInstance()
const { res_open_status } = proxy.useDict('res_open_status')

const resinfoList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const resCategoryList = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    resName: null,
    avgPrice: null,
    address: null,
    imgUrl: null,
    groupBuyCount: null,
    serviceTel: null,
    resDesc: null,
    userId: null,
    status: null,
    province: null,
    city: null,
    district: null,
    categoryId: null,
    notice: null,
    overallScore: null,
    field: null,
    resCategory: {
      categoryId: null,
      categoryName: null,
      field: null
    }
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询餐馆列表 */
function getList() {
  loading.value = true
  const userId = userStore.id;
  console.log('userId:', userId)
  if (userId && userId !== 1) {
    queryParams.value.userId = userId; // 如果用户 id 不为 1，则赋值给 queryParams 的 userId 字段
  }
  listResinfo(queryParams.value).then(response => {
    resinfoList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    resId: null,
    resName: null,
    avgPrice: null,
    address: null,
    imgUrl: null,
    groupBuyCount: null,
    serviceTel: null,
    resDesc: null,
    userId: null,
    status: null,
    province: null,
    city: null,
    district: null,
    categoryId: null,
    notice: null,
    overallScore: null,
    field: null,
    resCategory: {
      categoryId: null,
      categoryName: null,
      field: null
    }
  }
  proxy.resetForm("resinfoRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.resId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加餐馆"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _resId = row.resId || ids.value
  getResinfo(_resId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改餐馆"
    console.log(response)
  })
}

// 处理类别选择变化
function handleCategoryChange(newValue) {
  form.value.categoryId = newValue
  // 同时更新 resCategory 对象中的 categoryId
  form.value.resCategory.categoryId = newValue
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["resinfoRef"].validate(valid => {
    if (valid) {
      const userId = userStore.id;
      if (userId && userId !== 1) {
        form.value.userId = userId; // 在新增时将用户 ID 赋值给 form 的 userId 字段
      }
      if (form.value.resId != null) {
        updateResinfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addResinfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _resIds = row.resId || ids.value
  proxy.$modal.confirm('是否确认删除餐馆编号为"' + _resIds + '"的数据项？').then(function() {
    return delResinfo(_resIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/resinfo/export', {
    ...queryParams.value
  }, `resinfo_${new Date().getTime()}.xlsx`)
}

function getResCategoryList() {
  listResCategory().then(response => {
    resCategoryList.value = response.rows
  })
}

getList()
getResCategoryList()
</script>
